/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.sendsms.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 在这里编写类的功能描述
 *
 * @author duanlikao
 * @created 2020/11/30
 */
public class HttpClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    private static Integer timeout = 5000;

    public static String sendSSL(String url, String body, String contentType) throws Exception {

        //配置，发送https请求时，忽略ssl证书认证（否则会报错没有证书）
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        // 创建SSLClient连接客户端
        // CloseableHttpClient client = SSLClient.createSSLClient();
       // HttpClient client = HttpClientBuilder.create().build();

        //创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        // 创建url的post请求对象
        HttpPost post = new HttpPost(url);
        HttpEntity entity = new StringEntity(body, "utf-8");
        // 将请求信息装载到post的entity中
        post.setEntity(entity);
        if (contentType == null || "".equals(contentType)) {
            contentType = "text/html";
        }
        post.setHeader("Content-Type", contentType);
        // 请求url获取响应
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String resEntityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            // client.close();
            return resEntityStr;
        } else if (response.getStatusLine().getStatusCode() == 404) {
            //client.close();
            throw new Exception("Exception has occurred.");
        } else {
            // client.close();
            throw new Exception();
        }
    }

    public static String doGet(String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            //发送get请求
            HttpGet request = new HttpGet(url);
            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HttpClientUtil.timeout).
                    setConnectTimeout(HttpClientUtil.timeout).build();
            request.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(request);
//            LOGGER.info("doGet.response:url={} response={}", url, response);
            try {
                /**请求发送成功，并得到响应**/
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    /**读取服务器返回过来的json字符串数据**/
                    String strResult = EntityUtils.toString(response.getEntity());
//                    LOGGER.info("HttpClientUtil.doGet.res:url={} strResult={}", url, strResult);
                    return strResult;
                }
            } catch (Exception e) {
                LOGGER.error("doGet.exception: e={}", e);
            } finally {
                response.close();
            }

        } catch (Exception e) {
            LOGGER.error("HttpClientUtil.doGet.exception:url={} e={}", url, e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.error("doGet.exception:close client fail");
            }
        }

        return null;
    }
}